<?php

namespace App\Models\Order;

use App\Models\Currency;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * Class OrderTotal
 * @property string value
 * @property string symbol_left
 * @property string symbol_right
 * @package App\Models\Order
 *
 * @mixin Builder
 */

class OrderTotal extends Model
{
    const ORDER_TOTAL_VALUE_DEFAULT = 0.0000;

    const ORDER_TOTAL_CODE_TOTAL = 'total'; // 订单总金额

    const ORDER_TOTAL_CODE_REQUIRED = ['shipping', 'total', 'sub_total']; // 必须提交的统计信息

    protected $table = 'order_total';
    protected $guarded = [];
//    protected $appends = ['symbol_left', 'symbol_right'];

    public $timestamps = false;
    public $currency;

    /**
     * OrderTotal constructor.
     * @param array $attributes
     * @throws \Exception
     */
//    public function __construct(array $attributes = [])
//    {
//        parent::__construct($attributes);
//
//        $this->currency = Currency::fromEnv();
//    }

    /**
     * @return float|string
     * @throws \Exception
     */
//    public function getValueAttribute()
//    {
//        if (! $this->attributes['value']) return self::ORDER_TOTAL_VALUE_DEFAULT;
//
//        $currency = $this->currency;
//
//        return $currency->exchangePrice($this->attributes['value']);
//    }

    /**
     * @return mixed|string
     */
//    public function getSymbolLeftAttribute()
//    {
//        $currency = $this->currency;
//
//        return $currency->symbol_left;
//    }

    /**
     * @return mixed|string
     */
//    public function getSymbolRightAttribute()
//    {
//        $currency = $this->currency;
//
//        return $currency->symbol_right;
//    }

    /**
     * @param Order $order
     * @return OrderTotal|array
     */
    public static function getOrderTotalByTotal(Order $order)
    {
        $currency = Currency::getCurrencyByCode($order->currency_code);

        // 废弃了，用下面的。
//        $total = $order->orderTotalByTotal;
//        $total->symbol_left = $currency->symbol_left;
//        $total->symbol_right = $currency->symbol_right;
//        $total->value = $currency->exchangeOriginPrice($total->attributes['value'], $order->currency_value);
//        return $total;

        $total = $order->total;

        return [
            'symbol_left'  => $currency->symbol_left,
            'symbol_right' => $currency->symbol_right,
            'value'        => $currency->exchangeOriginPrice($total, $order->currency_value)
        ];
    }

}
